package col

import (
	"strings"
	tableConsts "yunj/pkg/yunj/core/builder/builderconsts"
	"yunj/pkg/yunj/core/builder/builderdto"
	"yunj/pkg/yunj/core/builder/table"
	"yunj/pkg/yunj/util"
)

// 枚举
type Enum struct {
	table.Col
	Options []builderdto.TableColOption `json:"options"` // 枚举选项
}

func NewEnum(field string, title ...string) *Enum {
	c := &Enum{}
	// 设置默认值
	c.Type = tableConsts.TABLE_COL_TYPE_NORMAL

	table.SetColInstance(&c.Col, c)
	c.SetColField(field)
	if len(title) > 0 {
		c.SetTitle(title[0])
	}
	return c
}

// 设置标题
func (c *Enum) SetTitle(title string) *Enum {
	c.Title = title
	return c
}

// 设置排列方式
func (c *Enum) SetAlign(align string) *Enum {
	c.Align = align
	return c
}

// 设置是否开启列的排序功能
func (c *Enum) SetSort(yes bool) *Enum {
	c.Sort = yes
	return c
}

// 设置固定列
func (c *Enum) SetFixed(fixed string) *Enum {
	c.Fixed = fixed
	return c
}

// 设置隐藏列
func (c *Enum) SetHide(hide string) *Enum {
	c.Hide = hide
	return c
}

// 设置宽度
func (c *Enum) SetWidth(width any) *Enum {
	c.Width = width
	return c
}

// 设置最小宽度
func (c *Enum) SetMinWidth(minWidth uint64) *Enum {
	c.MinWidth = minWidth
	return c
}

// 设置最大宽度
func (c *Enum) SetMaxWidth(maxWidth uint64) *Enum {
	c.MaxWidth = maxWidth
	return c
}

// 设置权限
func (c *Enum) SetAuth(auth string) *Enum {
	c.Auth = auth
	return c
}

// 设置枚举选项
func (c *Enum) SetOptions(options []builderdto.TableColOption) *Enum {
	c.Options = options
	return c
}

// 获取导出值
func (c *Enum) GetExportValue(value any) any {
	// 将值转换为字符串切片
	strValueSlice := []string{}
	if valueSlice, err := util.ToAnySlice(value); err == nil {
		for _, v := range valueSlice {
			if vStr, err := util.ToString(v); err == nil {
				strValueSlice = append(strValueSlice, vStr)
			}
		}
	} else {
		if valueStr, err := util.ToString(value); err == nil {
			strValueSlice = append(strValueSlice, valueStr)
		}
	}
	for _, option := range c.Options {
		optionStrValue, err := util.ToString(option.Value)
		if err != nil {
			continue
		}
		for i, strValue := range strValueSlice {
			if optionStrValue == strValue {
				if option.FullLabel != "" {
					strValueSlice[i] = option.FullLabel
				} else {
					strValueSlice[i] = option.Label
				}
			}
		}
	}
	return strings.Join(strValueSlice, "；")
}
